#include "DockingTabStack.h"
#include "DockingTabWell.h"
#include "DockTab.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QStackedWidget>
#include <QApplication>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QDebug>

DockingTabStack::DockingTabStack(DockingSplitter* parentSplitter, QWidget* parent)
    : QWidget(parent)
    , m_parentSplitter(parentSplitter)
    , m_tabWell(nullptr)
    , m_mainLayout(nullptr)
    , m_currentIndex(-1)
    , m_tabBarVisible(true)
    , m_tabPosition(Qt::TopEdge)
    , m_syncInProgress(false)
    , m_allowEmptyStack(false)
    , m_autoHideTabBar(true)
{
    setupTabStack();
}

DockingTabStack::~DockingTabStack()
{
    clear();
}

// === 初始化 ===

void DockingTabStack::setupTabStack()
{
    setupLayout();
    //setupConnections();
    
    // 设置拖放支持
    //setAcceptDrops(true);
    
    // 初始状态
   // updateTabWellVisibility();
}

void DockingTabStack::setupLayout()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);
    
    // 创建标签栏
    m_tabWell = new DockingTabWell(this, this);
    
    // 根据标签位置添加到布局
    setTabPosition(m_tabPosition);
}

void DockingTabStack::setupConnections()
{
    if (!m_tabWell ) return;
    
    // 连接TabWell信号
    connect(m_tabWell, &DockingTabWell::tabAdded, this, &DockingTabStack::onTabWellTabAdded);
    connect(m_tabWell, &DockingTabWell::tabRemoved, this, &DockingTabStack::onTabWellTabRemoved);
    connect(m_tabWell, &DockingTabWell::tabActivated, this, &DockingTabStack::onTabWellTabActivated);
    connect(m_tabWell, &DockingTabWell::tabMoved, this, &DockingTabStack::onTabWellTabMoved);
    connect(m_tabWell, &DockingTabWell::tabCloseRequested, this, &DockingTabStack::onTabWellTabCloseRequested);
    connect(m_tabWell, &DockingTabWell::tabPullOutRequested, this, &DockingTabStack::onTabWellTabPullOutRequested);
}

// === 标签页和内容管理 ===

DockTab* DockingTabStack::addTab(const QString& title, QWidget* content, int index)
{
    return addTab(QIcon(), title, content, index);
}

DockTab* DockingTabStack::addTab(const QIcon& icon, const QString& title, QWidget* content, int index)
{
    if (!content)
    {
        qWarning() << "DockingTabStack::addTab: content cannot be null";
        return nullptr;
    }
    
    // 创建标签页
    DockTab* tab = new DockTab(icon, title, this);
    tab->setContentWidget(content);
    
    // 设置标签类型（如果是第一个标签，则设为主标签）
    if (m_tabs.isEmpty())
    {
        tab->setTabType(DockTab::TabType::MainTab);
    }
    
    // 插入到指定位置
    if (index < 0 || index >= m_tabs.size())
    {
        index = m_tabs.size();
        m_tabs.append(tab);
        m_contents.append(content);
    }
    else
    {
        m_tabs.insert(index, tab);
        m_contents.insert(index, content);
    }
    
    // 添加到TabWell和ContentStack
    m_tabWell->addTab(tab, index, false); // 不保持非激活状态
    
    // 同步标签和内容
    syncTabWithContent(tab, content);
    
    // 更新可见性
    updateTabWellVisibility();
    
    // 发出信号
    emit tabAdded(tab, index);
    
    if (m_tabs.size() == 1)
    {
        emit stackBecameNonEmpty();
    }
    
    return tab;
}

void DockingTabStack::removeTab(DockTab* tab)
{
    int index = tabIndex(tab);
    if (index >= 0)
    {
        removeTab(index);
    }
}

void DockingTabStack::removeTab(int index)
{
    if (index < 0 || index >= m_tabs.size()) return;
    
    // 不允许删除基础标签（如果它是唯一的标签）
    if (index == 0 && m_tabs.size() == 1 && !m_allowEmptyStack)
    {
        qWarning() << "Cannot remove the last base tab";
        return;
    }
    
    // 开始同步操作
    m_syncInProgress = true;
    
    DockTab* tab = m_tabs.takeAt(index);
    m_contents.takeAt(index);
    
    // 调整当前索引
    if (m_currentIndex == index)
    {
        m_currentIndex = -1;
    }
    else if (m_currentIndex > index)
    {
        m_currentIndex--;
    }
    
    // 从TabWell和ContentStack移除
    m_tabWell->removeTab(tab);
    
    // 结束同步操作
    m_syncInProgress = false;
    
    // 确保有有效的当前标签
    ensureValidCurrentTab();
    
    // 更新可见性
    updateTabWellVisibility();
    
    // 发出信号
    emit tabRemoved(tab, index);
    
    if (m_tabs.isEmpty())
    {
        emit stackBecameEmpty();
    }
}

void DockingTabStack::clear()
{
    // m_syncInProgress = true;
    
    // while (!m_tabs.isEmpty())
    // {
    //     DockTab* tab = m_tabs.takeLast();
    //     QWidget* content = m_contents.takeLast();
        
    //     // 不删除内容widget，只是移除关联
    //     tab->setContentWidget(nullptr);
    //     content->setParent(nullptr);
        
    //     tab->deleteLater();
    // }
    
    // m_currentIndex = -1;
    // m_tabWell->clear();
    
    // // 清空ContentStack
    // while (m_contentStack->count() > 0)
    // {
    //     QWidget* widget = m_contentStack->widget(0);
    //     m_contentStack->removeWidget(widget);
    // }
    
    // m_syncInProgress = false;
    // updateTabWellVisibility();
    
    // emit stackBecameEmpty();
}

// === 激活状态管理 ===

void DockingTabStack::setCurrentTab(DockTab* tab) {
    int index = tabIndex(tab);
    if (index >= 0) {
        setCurrentTab(index);
    }
}

void DockingTabStack::setCurrentTab(int index) {
    if (index < 0 || index >= m_tabs.size() || index == m_currentIndex) {
        return;
    }
    
    if (m_syncInProgress) return;
    
    m_syncInProgress = true;
    
    // 更新内部状态
    m_currentIndex = index;
    
    // 同步TabWell和ContentStack
    m_tabWell->bringTabToFront(index);
    
    m_syncInProgress = false;
    
    // 发出信号
    emit currentChanged(index);
    emit currentTabChanged(m_tabs[index]);
    emit contentChanged(m_contents[index]);
}

DockTab* DockingTabStack::currentTab() const {
    if (m_currentIndex >= 0 && m_currentIndex < m_tabs.size()) {
        return m_tabs[m_currentIndex];
    }
    return nullptr;
}

int DockingTabStack::currentIndex() const {
    return m_currentIndex;
}

QWidget* DockingTabStack::currentContent() const {
    if (m_currentIndex >= 0 && m_currentIndex < m_contents.size()) {
        return m_contents[m_currentIndex];
    }
    return nullptr;
}

// === 标签页查询 ===

int DockingTabStack::tabCount() const {
    return m_tabs.size();
}

QList<DockTab*> DockingTabStack::tabs() const {
    return m_tabs;
}

DockTab* DockingTabStack::tabAt(int index) const {
    if (index >= 0 && index < m_tabs.size()) {
        return m_tabs[index];
    }
    return nullptr;
}

QWidget* DockingTabStack::contentAt(int index) const {
    if (index >= 0 && index < m_contents.size()) {
        return m_contents[index];
    }
    return nullptr;
}

int DockingTabStack::tabIndex(DockTab* tab) const {
    return m_tabs.indexOf(tab);
}

// === 布局管理 ===

bool DockingTabStack::isTabBarVisible() const {
    return m_tabBarVisible && m_tabWell->isVisible();
}

void DockingTabStack::setTabBarVisible(bool visible) {
    if (m_tabBarVisible != visible) {
        m_tabBarVisible = visible;
        updateTabWellVisibility();
    }
}

void DockingTabStack::setTabPosition(Qt::Edge edge) {
    if (m_tabPosition == edge) return;
    
    m_tabPosition = edge;
    
    // 重新排列布局
    m_mainLayout->removeWidget(m_tabWell);
    
    switch (edge) {
        case Qt::TopEdge:
            m_mainLayout->addWidget(m_tabWell);
            break;
            
        case Qt::BottomEdge:
            m_mainLayout->addWidget(m_tabWell);
            break;
            
        case Qt::LeftEdge:
        case Qt::RightEdge:
            // 水平布局（暂不支持，保持顶部）
            m_mainLayout->addWidget(m_tabWell);
            break;
    }
}

// === 特殊功能 ===

bool DockingTabStack::hasMainTab() const {
    for (DockTab* tab : m_tabs) {
        if (tab->tabType() == DockTab::TabType::MainTab) {
            return true;
        }
    }
    return false;
}

DockTab* DockingTabStack::mainTab() const
{
    for (DockTab* tab : m_tabs)
    {
        if (tab->tabType() == DockTab::TabType::MainTab)
        {
            return tab;
        }
    }
    return nullptr;
}

// === 拖拽集成 ===

bool DockingTabStack::acceptsTab(DockTab* tab) const
{
    // 基础检查
    if (!tab) return false;
    
    // 不接受已经在当前栈中的标签
    if (m_tabs.contains(tab)) return false;
    
    // 可以添加更多限制逻辑
    return true;
}

void DockingTabStack::adoptTab(DockTab* tab, int index)
{
    if (!acceptsTab(tab)) return;
    
    QWidget* content = tab->contentWidget();
    if (!content) return;
    
    // 移除标签的当前父容器关联
    tab->setParent(this);
    
    // 添加到当前栈
    if (index < 0 || index >= m_tabs.size())
    {
        index = m_tabs.size();
        m_tabs.append(tab);
        m_contents.append(content);
    }
    else
    {
        m_tabs.insert(index, tab);
        m_contents.insert(index, content);
    }
    
    // 添加到TabWell和ContentStack
    m_tabWell->addTab(tab, index, false);
    
    // 同步标签和内容
    syncTabWithContent(tab, content);
    
    // 更新可见性
    updateTabWellVisibility();
    
    emit tabAdded(tab, index);
    emit tabReturnedToStack(tab);
}

DockTab* DockingTabStack::releaseTab(int index) {
    if (index < 0 || index >= m_tabs.size()) return nullptr;
    
    DockTab* tab = m_tabs[index];
    QWidget* content = m_contents[index];
    
    // 移除但不删除
    m_tabs.removeAt(index);
    m_contents.removeAt(index);
    
    // 从TabWell和ContentStack移除
    m_tabWell->removeTab(tab);
    
    // 调整当前索引
    if (m_currentIndex == index)
    {
        m_currentIndex = -1;
        ensureValidCurrentTab();
    }
    else if (m_currentIndex > index)
    {
        m_currentIndex--;
    }
    
    // 移除父容器关联
    tab->setParent(nullptr);
    content->setParent(nullptr);
    
    updateTabWellVisibility();
    
    return tab;
}

// === Qt事件重写 ===

void DockingTabStack::resizeEvent(QResizeEvent* event) {
    QWidget::resizeEvent(event);
}

void DockingTabStack::showEvent(QShowEvent* event) {
    QWidget::showEvent(event);
    updateTabWellVisibility();
}

void DockingTabStack::hideEvent(QHideEvent* event) {
    QWidget::hideEvent(event);
}

// === 拖放支持 ===

void DockingTabStack::dragEnterEvent(QDragEnterEvent* event) {
    if (event->mimeData()->hasFormat("application/x-docktab")) {
        event->acceptProposedAction();
    } else {
        event->ignore();
    }
}

void DockingTabStack::dragMoveEvent(QDragMoveEvent* event) {
    if (event->mimeData()->hasFormat("application/x-docktab")) {
        event->acceptProposedAction();
    } else {
        event->ignore();
    }
}

void DockingTabStack::dragLeaveEvent(QDragLeaveEvent* event) {
    QWidget::dragLeaveEvent(event);
}

void DockingTabStack::dropEvent(QDropEvent* event) {
    if (event->mimeData()->hasFormat("application/x-docktab")) {
        // 获取拖拽的标签
        QByteArray data = event->mimeData()->data("application/x-docktab");
        quintptr tabPtr = data.toULongLong();
        DockTab* droppedTab = reinterpret_cast<DockTab*>(tabPtr);
        
        if (droppedTab && acceptsTab(droppedTab)) {
            adoptTab(droppedTab);
            event->acceptProposedAction();
        }
    }
}

// === TabWell事件处理 ===

void DockingTabStack::onTabWellTabAdded(DockTab* tab, int index) {
    if (!m_syncInProgress) {
        // TabWell主动添加标签，需要同步到Stack
        // 通常不会发生，因为都是通过Stack的addTab方法
    }
}

void DockingTabStack::onTabWellTabRemoved(DockTab* tab, int index) {
    if (!m_syncInProgress) {
        // TabWell主动移除标签，需要同步到Stack
        removeTab(index);
    }
}

void DockingTabStack::onTabWellTabActivated(DockTab* tab, int index) {
    if (!m_syncInProgress) {
        setCurrentTab(index);
    }
}

void DockingTabStack::onTabWellTabMoved(DockTab* tab, int fromIndex, int toIndex) {
    if (m_syncInProgress) return;
    
    m_syncInProgress = true;
    
    // 同步标签和内容列表
    m_tabs.move(fromIndex, toIndex);
    m_contents.move(fromIndex, toIndex);
    
    // 调整当前索引
    if (m_currentIndex == fromIndex) {
        m_currentIndex = toIndex;
    } else if (m_currentIndex > fromIndex && m_currentIndex <= toIndex) {
        m_currentIndex--;
    } else if (m_currentIndex < fromIndex && m_currentIndex >= toIndex) {
        m_currentIndex++;
    }

    m_syncInProgress = false;
    
    emit tabMoved(tab, fromIndex, toIndex);
}

void DockingTabStack::onTabWellTabCloseRequested(DockTab* tab) {
    emit tabCloseRequested(tab);
    removeTab(tab);
}

void DockingTabStack::onTabWellTabPullOutRequested(DockTab* tab, const QPoint& globalPos)
{
    emit tabPullOutRequested(tab, globalPos);
}

void DockingTabStack::syncTabWithContent(DockTab* tab, QWidget* content) {
    if (tab && content) {
        tab->setContentWidget(content);
        // 可以在这里添加更多同步逻辑
    }
}

// === 同步操作 ===

void DockingTabStack::syncCurrentTabWithContent()
{
    if (m_syncInProgress) return;
    
    int tabWellIndex = m_tabWell->foregroundTabIndex();
    
    if (m_currentIndex != tabWellIndex)
    {
        m_currentIndex = tabWellIndex;
    }
}

void DockingTabStack::ensureValidCurrentTab()
{
    if (m_tabs.isEmpty())
    {
        m_currentIndex = -1;
        return;
    }
    
    if (m_currentIndex < 0 || m_currentIndex >= m_tabs.size())
    {
        // 激活最后一个标签（按需求，拖出标签后显示最右边的）
        setCurrentTab(m_tabs.size() - 1);
    }
}

void DockingTabStack::updateTabWellVisibility()
{
    if (!m_tabWell) return;
    
    bool shouldShow = m_tabBarVisible &&  (!m_autoHideTabBar || m_tabs.size() > 1);
    
    m_tabWell->setVisible(shouldShow);
}

// === 工具函数 ===

int DockingTabStack::findContentIndex(QWidget* content) const
{
    return -1;
}

bool DockingTabStack::handleDropEvent(QDropEvent* event)
{
    // 直接调用protected的dropEvent方法
    dropEvent(event);
    return event->isAccepted();
}

void DockingTabStack::validateTabContentSync() const
{
    // Debug用：验证标签和内容的同步性
    Q_ASSERT(m_tabs.size() == m_contents.size());
    
    for (int i = 0; i < m_tabs.size(); ++i)
    {
        Q_ASSERT(m_tabs[i]->contentWidget() == m_contents[i]);
    }
}
